import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { loginApi, getUserInfoApi } from '../api/auth'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const username = computed(() => userInfo.value.username || '')
  const roles = computed(() => userInfo.value.roles || [])
  const permissions = computed(() => userInfo.value.permissions || [])

  // 检查是否有特定权限
  const hasPermission = (permission) => {
    if (!permission) return true
    return permissions.value.includes(permission)
  }

  // 检查是否有特定角色
  const hasRole = (role) => {
    if (!role) return true
    return roles.value.includes(role)
  }

  // 检查是否有多个权限中的任意一个
  const hasAnyPermission = (permissionList) => {
    if (!permissionList || permissionList.length === 0) return true
    return permissionList.some(permission => hasPermission(permission))
  }

  // 检查是否有多个角色中的任意一个
  const hasAnyRole = (roleList) => {
    if (!roleList || roleList.length === 0) return true
    return roleList.some(role => hasRole(role))
  }
  
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }
  
  const setUserInfo = (info) => {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  
  const getUserInfo = async () => {
    try {
      const res = await getUserInfoApi()
      if (res.status === 0) {
        setUserInfo(res.data)
        return res.data
      }
      return Promise.reject(new Error(res.message || '获取用户信息失败'))
    } catch (error) {
      return Promise.reject(error)
    }
  }
  
  const login = async (credentials) => {
    try {
      const res = await loginApi(credentials)
      if (res.status === 0) {
        setToken(res.token)
        await getUserInfo()
        ElMessage.success('登录成功')
        return res
      }
      return Promise.reject(new Error(res.message || '登录失败'))
    } catch (error) {
      ElMessage.error(error.message || '登录失败')
      return Promise.reject(error)
    }
  }
  
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    ElMessage.success('已退出登录')
  }
  
  return { 
    token, 
    userInfo, 
    isLoggedIn,
    username,
    roles,
    permissions,
    hasPermission,
    hasRole,
    hasAnyPermission,
    hasAnyRole,
    login, 
    logout, 
    getUserInfo,
    setToken, 
    setUserInfo 
  }
})